﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using SMS.WinForms;

namespace SMS.Console.Controls
{
    public class ConnectionTestButton : Button
    {
        public class ConnectionStringRequestArgs : EventArgs
        {
            public string ConnectionString { get; set; }
        }
        public event EventHandler<ConnectionStringRequestArgs> ConnectionStringRequest;
        public ConnectionTestButton()
        {
        }

        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
            Form form = this.FindForm();
            try
            {
                form.Cursor = Cursors.WaitCursor;
                if (ConnectionStringRequest == null)
                    throw new InvalidOperationException("未订阅ConnectionStringRequest事件。");
                ConnectionStringRequestArgs request = new ConnectionStringRequestArgs();
                ConnectionStringRequest(this, request);
                SqlUtility.TestConnection(request.ConnectionString);
                UIHelper.Alert("连接成功！");
            }
            catch (SqlException ex)
            {
                Exception newException = new Exception("连接服务器失败", ex);
                ErrorBox.Show(newException);
            }
            catch (Exception ex)
            {
                ErrorBox.Show(ex);
            }
            finally
            {
                form.Cursor = Cursors.Default;
            }
        }
    }
}
